﻿using System;
using System.Data;
using System.Web.UI.WebControls;
using System.IO;

using BLL;
using Model;
using Utility;

namespace EvaluationSystem
{
    public partial class PositionList : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ((SiteSystemMaster)Master).InitMenu();
            ((SiteSystemMaster)Master).li2.Attributes.Add("class", "hover ccc");
            ((SiteSystemMaster)Master).b_hmenu1.Style.Add("display", "none");
            ((SiteSystemMaster)Master).b_hmenu2.Style.Clear();
            ((SiteSystemMaster)Master).b_hmenu3.Style.Add("display", "none");
            ((SiteSystemMaster)Master).s_menu2_1.Style.Add("COLOR", "#147ab8");
            ((SiteSystemMaster)Master).s_menu2_1.Style.Add("TEXT-DECORATION", "none"); 

            /*判断是否是管理员身份*/
            if (Session["username"] == null)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "PopupScript", "<script>alert('请先登录系统!');top.location.href='../System/Login.aspx';</script>");
                return;
            }
            else
            {
                if (!IsPostBack)
                {
                    PositionBLL temp = new PositionBLL();
                    DataSet ds = temp.GetPositionAll("");

                    grVPositionManage.DataSource = ds.Tables[0].DefaultView;
                    grVPositionManage.DataSourceID = null;
                    grVPositionManage.DataBind();
                    temp = null;
                }
            }
        }

        protected void CB_SelectAll_CheckedChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < this.grVPositionManage.Rows.Count; i++)
            {
                GridViewRow gr = this.grVPositionManage.Rows[i];
                CheckBox chk = (CheckBox)gr.Cells[0].FindControl("CB_Select");
                chk.Checked = this.CB_SelectAll.Checked; //跟随全选按扭的状态变化;
            }
        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int rowIndex = Int32.Parse(e.CommandArgument.ToString());//获取点击了第几行
            int posID = Int32.Parse(grVPositionManage.DataKeys[rowIndex].Values[0].ToString());

            if (e.CommandName == "DimSetting")
            {
                Response.Redirect("~/System/DimensionSet.aspx?mode=0&posid=" + posID.ToString());
            }
            if (e.CommandName.Equals("Export") || e.CommandName.Equals("ExportNewData"))//答题信息导出 or 数据导出
            {
                PositionBLL temp = new PositionBLL();
                DimensionBLL dBll = new DimensionBLL();

                DataSet dimDS = dBll.GetDimensionAll();
                DataSet dsAll = new DataSet();

                for (int i = 0; i < dimDS.Tables[0].Rows.Count; i++)
                {
                    int dimID = Int32.Parse(dimDS.Tables[0].Rows[i][0].ToString());
                    DataSet dsa =  temp.GetExportDSIncAllDim(posID,dimID);
                    dsa.Tables[0].TableName = dBll.GetDimension(dimID.ToString()).Dimnm;
                    dsAll.Tables.Add(dsa.Tables[0].Copy());            
                }

                //2012.3.14，岗位导出时删除无关维度表 begin.
                for (int i = dsAll.Tables.Count - 1; i >= 0; i--)
                {
                    if (dsAll.Tables[i].Rows.Count < 1)
                    {
                        dsAll.Tables.Remove(dsAll.Tables[i]);
                    }
                }
                dsAll.AcceptChanges();
                //2012.3.14，岗位导出时删除无关维度表 end.

                //新的导出格式---数据导出
                DataSet dsPivot = new DataSet();
                if (e.CommandName.Equals("ExportNewData"))
                {
                    //开始进行pivot                    
                    string activityName = string.Empty;
                    string testerName = string.Empty;

                    TesterInfoBLL tbll = new TesterInfoBLL();
                    ActivityBLL abll = new ActivityBLL();
                    GuidBLL gbll = new GuidBLL();

                    foreach (DataTable t in dsAll.Tables)
                    {
                        Pivot p = new Pivot(t);
                        DataTable dt = p.PivotData("序列号", "原始得分", AggregateFunction.Sum, "题目编号");
                        p = null;
                        dt.TableName = t.TableName;
                        dt.Columns.Add("项目名称").SetOrdinal(0);
                        dt.Columns.Add("姓名").SetOrdinal(1);

                        foreach (DataRow row in dt.Rows)
                        {
                            string guid = row["序列号"].ToString();
                            row["项目名称"] = abll.GetActivityNM(gbll.GetActivityId(guid));
                            row["姓名"] = tbll.GetUserNameByGUID(guid);
                        }
                        dsPivot.Tables.Add(dt);
                    }
                    //pivot结束
                }
                string filePath = Server.MapPath("../userfiles") + @"\position_" + DateTime.Now.ToString("yyyyMMdd_HH_mm_ss") + ".xls";
                string fileName = Path.GetFileName(filePath);
                
                if (e.CommandName.Equals("Export"))//原始格式--答题信息导出
                {
                    //2013.10.22 add by conghui for export issue begin.
                    foreach (DataTable dt in dsAll.Tables)
                    {
                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            for (int j = 0; j < dt.Rows.Count; j++)
                            {
                                if (dt.Rows[j][i] == DBNull.Value || dt.Rows[j][i] == null)//如果单元格为空
                                {
                                    if (i == 2)//第二列是日期列
                                    {
                                        dt.Rows[j][i] = "1900-1-1";
                                    }
                                    else
                                    {
                                        dt.Rows[j][i] = "";
                                    }
                                }
                                else//单元格非空
                                {
                                    if (i == 2)//将日期强制转化为字符串
                                    {
                                        dt.Rows[j][i] = dt.Rows[j][i].ToString();
                                    }
                                }
                            }
                        }
                    }
                    //2013.10.22 add by conghui for export issue end.

                    ExcelLibrary.DataSetHelper.CreateWorkbook(filePath, dsAll);
                }
                else if (e.CommandName.Equals("ExportNewData"))//新的格式--答题数据导出
                {
                    ExcelLibrary.DataSetHelper.CreateWorkbook(filePath, dsPivot);
                }

                Stream stream = null;
                stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                long bytesToRead = stream.Length;
                Response.Clear();
                Response.ContentType = "application/ms-excel";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);

                while (bytesToRead > 0)
                {
                    if (Response.IsClientConnected)
                    {
                        byte[] buffer = new Byte[10000];
                        int length = stream.Read(buffer, 0, 10000);
                        Response.OutputStream.Write(buffer, 0, length);
                        Response.Flush();
                        bytesToRead = bytesToRead - length;
                    }
                    else
                    {
                        bytesToRead = -1;
                    }
                }
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            PositionBLL temp = new PositionBLL();
            int selectCount = 0;
            int position_id = 0;
            foreach (GridViewRow gr in grVPositionManage.Rows)
            {
                CheckBox chk = (CheckBox)gr.Cells[0].FindControl("CB_Select");
                if (chk.Checked)
                {
                    position_id = int.Parse(grVPositionManage.DataKeys[gr.RowIndex].Values["position_id"].ToString());

                    temp.Delete(position_id);
                    selectCount++;
                }
            }
            if (0 == selectCount)
            {
                MessageBox.ShowAndRedirect(this, "请选择一个岗位", "PositionList.aspx");
            }
            temp = null;
            MessageBox.ShowAndRedirect(this, "删除操作成功", "PositionList.aspx");
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/System/AddPosition.aspx");
        }
    }
}